package com.itany.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.itany.cloud.exception.GlobalSentinelException;
import com.itany.cloud.util.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping
public class HelloController {

    @RequestMapping("/f1")
    @SentinelResource(value = "f1", blockHandler = "handlerException")
    public ResponseResult f1() {
        return ResponseResult.success();
    }

    public ResponseResult handlerException(BlockException e) {
        return ResponseResult.fail("Sentinel异常,异常为:" + e);
    }

    @RequestMapping("/f2")
    @SentinelResource(value = "f2", blockHandlerClass = GlobalSentinelException.class, blockHandler = "handlerException")
    public ResponseResult f2() {
        return ResponseResult.success();
    }

    @RequestMapping("/f3")
    @SentinelResource(value = "f3", blockHandlerClass = GlobalSentinelException.class, blockHandler = "handlerException")
    public ResponseResult f3() {
        System.out.println("当前时间:" + System.currentTimeMillis());
        return ResponseResult.success();
    }

    @RequestMapping("/f4/{id}")
    public ResponseResult f4(@PathVariable Integer id) {
        if (id == 1) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.success();
    }

    @RequestMapping("/f5/{id}")
    public ResponseResult f5(@PathVariable Integer id) {
        int i = 1 / id;
        return ResponseResult.success();
    }

    @RequestMapping("/f6")
    @SentinelResource(value = "f6", blockHandler = "handlerException2")
    public ResponseResult f6(String s1, String s2) {
        return ResponseResult.success("f6执行成功,第一个参数为:" + s1 + ",第二个参数为:" + s2);
    }

    public ResponseResult handlerException2(BlockException e) {
        return ResponseResult.fail("Sentinel热点限流");
    }

    @RequestMapping("/f7")
    public ResponseResult f7(){
        return ResponseResult.success("授权通过");
    }
}
